/**
 *
 * pH.Data
 *
 * Configuration Options:		
 * 
 *	url:    URL of pH Data File.
 *	update: Callback function to execute when Data is updated (Sort/Search)	
 *	cache:  Whether or not to cache data.
 *
 */

pH.Data = function(config)
{
	var config = jQuery.extend({
		cache: false,
		url: '',
		update: false
	}, config);

	this.data_cache = null;
	this.url = config.url;

	// Synchronization Stuff
	this.updating = false;

	if (config.update)
		$(this).bind("update", config.update);

	var self = this;

	var on_update = function(data)
	{
		$(self).trigger("update", [data]);

		if (config.cache && self.data_cache == null)
			self.data_cache = data;

		self.updating = false;
	}
	
	this.get = function () {
		if (self.updating) return;

		self.updating = true;

		if (config.cache && self.data_cache)
			on_update(data_cache);
		else			
			$.getJSON(config.url, null, on_update );
	};

	this.fields = function() 
	{
		var result = [];
		var d;

		if (config.cache && self.data_cache)
			d = self.data_cache;
		else
			$.getJSON(config.url, null, function(data) { d = data; });
		
		for (i in d)
			result.push(i);

		return result;
	};

	$(self).trigger("ready");

}

pH.info('pH+ Data module successfully enabled.');
